package com.hebeiwangxiaozhang.canal.listener;

import com.alibaba.fastjson.JSONObject;
import com.hebeiwangxiaozhang.canal.config.RedisConfig;
import com.hebeiwangxiaozhang.canal.pojo.CanalMessage;
import com.hebeiwangxiaozhang.canal.utils.RedisCommonProcessor;
import com.rabbitmq.tools.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class CanalRabbitMQListener {

    @Autowired
    private RedisCommonProcessor redisCommonProcessor;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = "canal.queue", durable = "true"),
                    exchange = @Exchange(value = "canal.exchange"),
                    key = "canal.routing.key"
            )
    })
    public void handleDataChange(String message) {
        //将message转换为CanalMessage
        CanalMessage msg = JSONObject.parseObject(message, CanalMessage.class);
        if(msg.getTable().equals("user") && msg.getDatabase().equals("oauth") &&
                !msg.getType().equals("INSERT")) {
            List<Map<String, Object>> dataSet= msg.getData();
            for(Map data : dataSet) {
                String id = String.valueOf(data.get("id"));
                if(id != null) {
                    redisCommonProcessor.del(Integer.valueOf(id) + 10000000);
                }
            }
        }
    }
}